package com.als;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;


@Slf4j
public class AlsModel implements Serializable {


    public static boolean writeTxtFile(String newStr) throws IOException {
        boolean flag;
        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {

            File file = new File("model.md");
            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(newStr.toCharArray());
            pw.flush();
            flag = true;
        } catch (Exception e) {
            flag = false;
            log.info("输出文件失败：{}", e.getMessage());
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
        }

        return flag;
    }

    public void train() {
        try {
            Connection conn = AlsDB.getConn();
            Statement st = conn.createStatement();
            String sql = "SELECT userid,refid,COUNT(*) AS score FROM storeup GROUP BY userid,refid";
            ResultSet rs = st.executeQuery(sql);
            StringBuffer stringBuffer = new StringBuffer();
            int i = 0;
            while (rs.next()) {
                if (i != 0) {
                    stringBuffer.append("\r\n");
                }
                stringBuffer.append(rs.getLong("userid") + "," + rs.getLong("refid") + "," + rs.getInt("score"));
                i++;
            }
            writeTxtFile(stringBuffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void insertR(int uid, int pid) {
        try {
            Connection conn = AlsDB.getConn();
            Statement statement = conn.createStatement();
            statement.executeUpdate("insert into rec(zid,uid) values (" + pid + "," + uid + ")");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void delR() {
        try {
            Connection conn = AlsDB.getConn();
            Statement statement = conn.createStatement();
            statement.executeUpdate("delete from  rec ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
